#include <stdio.h>
#include <stdlib.h>

// 每次重新分配多分配10个字节
#define ALLOC_STEP 10

int mygetline(char **line, int *n);

char *mystrchr(const char *str, char c);

char *mystrstr(const char *str, const char *sub);

int main(void)
{
	//char *a = "Hello, world!";
	char* a;
	int size = 0;
	int count;
	char *b = "orl";
	char *c = "UwU";

	count = mygetline(&a, &size);
	printf("输入的字符串：%s\n", a);
	printf("buffer大小：%d\n", size);
	printf("实际字符个数（包含'\\n'）：%d\n", count);

    mystrchr(a, 'w');
	mystrchr(a, 'c');

	mystrstr(a, b);
	mystrstr(a, a);
	mystrstr(a, c);

	return 0;
}

int mygetline(char **line, int *n)
{
	int count = 0;
	char c;

	do {
		scanf("%c", &c);
		count++;

		if (count >= (*n)) { // 等于的时候还需要一个位置放'\0'，也需要扩容
			if (*n == 0 || *line == NULL) {
				//printf("初次分配（%d）\n", ALLOC_STEP);
				*line = malloc(ALLOC_STEP);
				*n = ALLOC_STEP;
			} else {
				//printf("再分配（%d + %d）\n", *n, ALLOC_STEP);
				*line = realloc(*line, (*n) + ALLOC_STEP);
				*n += ALLOC_STEP;
			}
		}

		(*line)[count - 1] = c; // 要求保留输入中的'\n'

	} while (c != '\n');

	(*line)[count] = '\0';

	return count;
}

int mystrlen(const char *str)
{
	int i = 0;

	while (str[i]) {
		i++;
	}

	return i;
}

char *mystrchr(const char *str, char c)
{
	int i;

	for (i = 0; str[i]; i++) {
		if (str[i] == c) {
			printf("在%d处找到了字符%c\n", i, c);
			return (char *) str + i;
		}
	}

	printf("未找到字符%c\n", c);
	return NULL;
}

char *mystrstr(const char *str, const char *sub)
{
	int sublen = 0;
	int strlen = 0;
	int i, j;
	int match;

	sublen = mystrlen(sub);
	strlen = mystrlen(str);

	for (i = 0; i <= strlen - sublen; i++) {
		match = 1;

		for (j = 0; j < sublen; j++) {
			if (str[i + j] != sub[j]) {
				match = 0;
				break;
			}
		}

		if (match) {
			printf("在%d处找到了子串%s\n", i, sub);
			return (char *) str + i;
		}
	}

	printf("未找到子串%s\n", sub);
	return NULL;
}


